"use strict";

/**
 * @auther wtfssd
 * Created by wtfssd on 2017/11/16
 */
import * as React from 'react'

const {View, ImageBackground, TouchableOpacity, ScrollView, StyleSheet, Alert} = require('react-native');
const {connect} = require('react-redux');
import {SCREEN_HEIGHT, SCREEN_WIDTH} from "../../constant"

const NavigationBar = require('react-native-navbar').default;
import {autoSize, commonProps, commonStyles} from "../../assets/styles/common";
import NavBackButton from "../../component/BackButton";
import MyImagePicker from "../../component/MyImagePicker";

const {KeyboardAwareScrollView} = require('react-native-keyboard-aware-scroll-view');
import Colors from "../../assets/styles/Colors";
import MyText from "../../component/MyText";
import MyIcon from "../../component/icon";
import {iconProps} from "../../component/index";
import {ReactNode} from "react";
import Line from "../../component/Line";
import {getValueFromArray, toastValidateError} from "../../utils/tools";
import Request from "../../utils/Request";
import NavRightButton from "../../component/RightButton";
import {CategoryItem, ProductItem, ProductManagerProps, TopCategoryItem} from "../../interface/index";

const {Actions} = require("react-native-router-flux");

const {createForm} = require('rc-form');

const {List, InputItem, Picker, Button, TextareaItem, Switch} = require('antd-mobile');
let TextAreaStyle = require('antd-mobile/lib/textarea-item/style/index.native');
const newStyle = {};

for (const key in TextAreaStyle) {
    if (Object.prototype.hasOwnProperty.call(TextAreaStyle, key)) {
        newStyle[key] = {...StyleSheet.flatten(TextAreaStyle[key])};
        if (key === 'container') {
            newStyle[key].marginLeft = 0;
            newStyle[key].borderBottomWidth = 0;
            newStyle[key].borderBottomColor = 'transparent';
        }
    }
}

interface AddProductPageListItemProps {
    extra?: ReactNode | any,
    onClick?: Function,
    title?: string,
    content?: string,
    placeHolder?: string,

}

class AddProductPageListItem extends React.Component<AddProductPageListItemProps, any> {


    content: any;
    extra: any;

    constructor(props: any, context: any) {
        super(props, context);
        this.extra = props.extra;


    }


    static defaultProps = {
        title: '',
        placeHolder: null,
        content: null,

    };

    componentWillMount(): void {
    }


    render() {


        const isEmpty = () => {
            return !this.props.content
        };

        return (
            <TouchableOpacity onPress={this.props.onClick} style={[commonStyles.flexRow
                , commonStyles.relative, {alignItems: 'center', justifyContent: 'space-between', padding: 10}]}>
                <View style={[commonStyles.flex1, commonStyles.flexRow, {alignItems: 'center'}]}>
                    <MyText fontSize={16}>{this.props.title}</MyText>
                    <MyText fontSize={16} style={{marginLeft: 10}}
                            color={!isEmpty() ? '#666666' : '#999999'}>{!isEmpty() ? this.props.content : this.props.placeHolder}</MyText>
                </View>
                {this.extra}
                <Line style={[commonStyles.absolute, {bottom: 0, right: 0, width: autoSize(SCREEN_WIDTH - 10)}]}/>
            </TouchableOpacity>
        )
    }
}


interface AddProductPageProps extends ProductManagerProps {
    actionType: 'new' | 'edit',
    editProduct?: ProductItem
}

class AddProductPage extends React.Component<AddProductPageProps, any> {


    static defaultProps = {
        actionType: 'new',
        title: '添加商品'
    };

    imagePicker: MyImagePicker;


    constructor(props: any, context: any) {
        super(props, context);
        this.state = {
            preview: null,
        };
        this.imagePicker = new MyImagePicker();
        this.imagePicker.options.pickerOptions.allowsEditing = true;
        this.imagePicker.options.cropOptions.width = SCREEN_WIDTH;
        this.imagePicker.options.cropOptions.height = autoSize(SCREEN_WIDTH);
    }


    componentWillMount(): void {
        this.props.dispatch({
            type: 'product/fetchTopCategories'
        })
    }


    //格式化数据
    static formatPickerData(array: Array<any>, label: string, value: string) {
        return array.map(item => {
            return {label: item[label], value: parseInt(item[value])}
        })
    }

    static getExtraItem(icon: iconProps, onPress: Function = null) {
        if (onPress) {
            return (
                <TouchableOpacity onPress={Actions.customMenu}>
                    <MyIcon {...icon} size={20}/>
                </TouchableOpacity>
            )
        } else {
            return <MyIcon size={20} {...icon} />
        }
    }


    selectedHeaderImage = (key: string) => {
        this.imagePicker.showImagePicker().then(response => {
            this.setState({
                preview: {
                    uri: response['path'],
                    type: 'application/octet-stream',
                    name: response['fileName'] ? response['fileName'] : 'afgdahfty2345379243t6qeghasdg.jpg'
                }
            });
        }).catch(e => {
            console.log(e);
        })
    };
    onLoadNetImage = (e, p) => {
        console.log('end', e.nativeEvent, p);
    };
    renderHeader = () => {
        let source = {};
        if (this.props.actionType === 'new') {
            source = this.state.preview ? {uri: this.state.preview.uri} : (require('../../assets/image/background.png'))
        } else {
            source['uri'] = this.state.preview ? this.state.preview.uri : Request.checkImageUrl(this.props.editProduct.get_douct_info.preview);
        }
        return (
            <TouchableOpacity onPress={this.selectedHeaderImage.bind(this, 'shop_image')}>
                <ImageBackground style={[commonStyles.centerVH, {width: SCREEN_WIDTH, height: autoSize(SCREEN_WIDTH)}]}

                                 onLoad={this.props.actionType === 'new' ? null : this.onLoadNetImage}
                                 source={source}
                >

                </ImageBackground>
            </TouchableOpacity>


        )
    };


    onDelete = () => {
        Alert.alert(
            '删除该商品?',
            '',
            [
                {
                    text: '确定', onPress: () => {
                    this.props.dispatch({
                        type: 'product/del',
                        payload: {product_id: this.props.editProduct.get_douct_info.id}
                    })
                }
                },
                {
                    text: '取消', onPress: () => {

                }, style: 'cancel'
                },
            ],
            {cancelable: true}
        )
    };

    onCreate = () => {
        const {dispatch, form} = this.props;


        form.validateFields((error, value) => {
            if (!error) {
                value.category_id = Array.isArray(value.category_id) ? value.category_id[0] : value.category_id;
                value.store_data_id = Array.isArray(value.store_data_id) ? value.store_data_id[0] : value.store_data_id;
                value['is_shelves'] = value['is_shelves'] === true ? 1 : 0;
                value['is_recommend'] = value['is_recommend'] === true ? 1 : 0;
                let payload = {...value,};
                if (this.props.actionType === 'edit') {
                    payload['product_id'] = this.props.editProduct.get_douct_info.id;
                    if (this.state.preview) {
                        payload['preview'] = this.state.preview
                    }
                } else {
                    if (!this.state.preview) {
                        toastValidateError(null, '请选择商品图片');
                        return;
                    } else {
                        payload['preview'] = this.state.preview;
                    }
                }

                const type = this.props.actionType === 'new' ? 'product/add' : 'product/edit';
                dispatch({
                    type,
                    payload: {...payload}
                })

            } else {
                toastValidateError(error);
            }
        });
    };

    render() {
        const {getFieldProps} = this.props.form;


        let category_name1 = null;
        let category_name2 = null;

        if (this.props.actionType === 'new') {
            const category_id = this.props.form.getFieldValue('category_id');
            const store_data_id = this.props.form.getFieldValue('store_data_id');
            let item1: TopCategoryItem = getValueFromArray(this.props.product.topCategoryList, 'category_id', category_id);
            category_name1 = item1 ? item1.category_name : null;
            let item2: CategoryItem = getValueFromArray(this.props.product.categoryList, 'id', store_data_id);
            category_name2 = item2 ? item2.store_menu : null;
        }
        else {

            let category_id = this.props.form.getFieldValue('category_id');
            let store_data_id = this.props.form.getFieldValue('store_data_id');

            category_id = category_id ? (Array.isArray(category_id) ? category_id[0] : category_id) : this.props.editProduct.get_douct_info.category_id;
            store_data_id = store_data_id ? ( Array.isArray(store_data_id) ? store_data_id[0] : store_data_id) : this.props.editProduct.store_data_id;

            this.props.product.topCategoryList.map((item: TopCategoryItem) => {
                if (item.category_id == category_id) {
                    category_name1 = item.category_name;
                }
            });

            this.props.product.categoryList.map((item: CategoryItem) => {
                if (item.id == store_data_id) {
                    category_name2 = item.store_menu;
                }
            });
        }
        return (
            <View style={commonStyles.container}>
                <NavigationBar {...commonProps.navBar}
                               leftButton={<NavBackButton/>}
                               rightButton={this.props.actionType === 'edit' ?
                                   <NavRightButton onPress={this.onDelete}>删除</NavRightButton> : null}
                               title={{title: this.props.title, tintColor: '#fff'}}
                />
                <KeyboardAwareScrollView keyboardOpeningTime={50} keyboardDismissMode={'on-drag'}>
                    <List renderHeader={this.renderHeader}>
                        <Picker
                            {...getFieldProps('category_id', {
                                initialValue: this.props.actionType === 'new' ? null : this.props.editProduct.get_douct_info.category_id,
                                rules: [
                                    {required: true, message: '分类菜单未选择'},
                                ]
                            })}
                            data={AddProductPage.formatPickerData(this.props.product.topCategoryList, 'category_name', 'category_id')}
                            extra={AddProductPage.getExtraItem({name: 'icon-jiantouxia', color: '#666'})}
                            title="分类"
                            cols={1}
                        >
                            <AddProductPageListItem title={'分类菜单'} placeHolder={'请选择分类菜单'}
                                                    content={category_name1}/>

                        </Picker>

                        <Picker
                            {...getFieldProps('store_data_id', {
                                initialValue: this.props.actionType === 'new' ? null : this.props.editProduct.store_data_id,
                                rules: [
                                    {required: true, message: '自定义菜单未选择'},
                                ]
                            })}
                            data={AddProductPage.formatPickerData(this.props.product.categoryList, 'store_menu', 'id')}
                            extra={AddProductPage.getExtraItem({
                                name: 'icon-icon19',
                                color: 'red',
                                size: 16
                            }, Actions.customMenu)}
                            title="自定义分类"
                            cols={1}
                        >
                            <AddProductPageListItem title={'自定义菜单'} placeHolder={'请选择自定义菜单'}
                                                    content={category_name2}/>

                        </Picker>

                        <InputItem
                            {...getFieldProps('name', {
                                initialValue: this.props.actionType === 'new' ? null : this.props.editProduct.get_douct_info.name,
                                rules: [
                                    {required: true, message: '商品名称未填写'},
                                ]
                            })}
                            placeholder='输入商品名称' clear
                            labelNumber={4}>商品名称</InputItem>
                        <InputItem
                            {...getFieldProps('spec', {
                                initialValue: this.props.actionType === 'new' ? null : this.props.editProduct.get_douct_info.spec,
                                rules: [
                                    {required: true, message: '商品规格未填写'},
                                ]
                            })}
                            placeholder='输入店商品规格'
                            clear
                            labelNumber={4}>{`规        格`}</InputItem>


                        <InputItem
                            {...getFieldProps('price', {
                                initialValue: this.props.actionType === 'new' ? null : this.props.editProduct.get_douct_info.price,
                                rules: [
                                    {required: true, message: '商品价格未填写'},
                                ]
                            })}
                            placeholder='输入商品价格'
                            type={'number'}
                            clear
                            labelNumber={4}>{`价       格`}</InputItem>

                        <List.Item
                            extra={
                                <Switch {...getFieldProps('is_recommend', {
                                    initialValue: this.props.actionType === 'new' ? false : Number(this.props.editProduct.is_recommend) === 1,
                                    valuePropName: 'checked',
                                })} />
                            }
                        >热销单品</List.Item>


                        <List.Item
                            extra={
                                <Switch {...getFieldProps('is_shelves', {
                                    initialValue: this.props.actionType === 'new' ? true : Number(this.props.editProduct.get_douct_info.is_shelves) === 1,
                                    valuePropName: 'checked',
                                })} />
                            }
                        >上架</List.Item>


                        <View style={{padding: 14}}>
                            <MyText color={Colors.Black}>商品详情</MyText>
                            <View style={{paddingHorizontal: 20}}>
                                <View style={{
                                    borderWidth: 1,
                                    borderColor: '#d0d0d0',
                                    borderRadius: 10,
                                    padding: 5,
                                    marginTop: 10
                                }}>
                                    <TextareaItem
                                        {...getFieldProps('summary', {
                                            initialValue: this.props.actionType === 'new' ? null : this.props.editProduct.get_douct_info.summary,
                                            rules: [
                                                {required: true, message: '商品详情未填写'},
                                            ]
                                        })}
                                        placeholder='请输入商品简介'
                                        styles={StyleSheet.create(newStyle)}
                                        rows={5}
                                        count={100}
                                    />
                                </View>
                            </View>
                        </View>

                        <View style={{padding: 10}}>
                            <Button type={'primary'} style={{height: 30}}
                                    onClick={this.onCreate}>{this.props.actionType === 'new' ? '添加商品' : '保存修改'}</Button>
                        </View>
                    </List>

                </KeyboardAwareScrollView>


            </View>
        );
    }
}


const Wrapper = createForm(
    {
        onValuesChange: (e1, e2) => {
            console.log(e1, e2, this)
        }
    }
)(AddProductPage);

export default connect(
    ({auth, product}) => ({auth, product})
)(Wrapper);

/*
* extra={((p) => {
                        return (
                            <MyIcon name={'icon-jiantouxia'} color={'#666'} size={10}/>
                        )
                    })()}*/


/*
* extra={((p) => {
                            return (
                                <TouchableOpacity onPress={Actions.customMenu}>
                                    <MyIcon name={'icon-icon19'} color={'red'} size={20}/>
                                </TouchableOpacity>
                            )
                        })()}*/